package com.black.utils.file.image;

import com.black.utils.file.FileTypeEnum;
import org.w3c.dom.NodeList;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.media.jai.JAI;
import javax.media.jai.RenderedOp;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * @author ylx
 */
public class ImageLoadUtil {
    public static final String LOAD = "fileload";

    @Deprecated
    public static ImageInfo load(String fileName) {
        try {
            if (!FileTypeEnum.isImage(fileName)) {
                throw new IllegalArgumentException("文件类型错误或不支持的类型");
            }
            RenderedOp image = JAI.create(LOAD, fileName);
            int width = image.getWidth();
            int height = image.getHeight();
            // 使用ImageIO获取图像的元数据
            File file = new File(fileName);
            long size = file.length();
            ImageInputStream iis = ImageIO.createImageInputStream(new File(fileName));
            Iterator<ImageReader> imageReaders = ImageIO.getImageReaders(iis);
            if (!imageReaders.hasNext()) {
                throw new IllegalArgumentException("无法获取图像元数据");
            }
            ImageReader imageReader = imageReaders.next();
            imageReader.setInput(iis, true);
            IIOMetadata metadata = imageReader.getImageMetadata(0);

            // 提取分辨率信息
            double dpiX = 0.0;
            double dpiY = 0.0;
            String type = FileTypeEnum.getExtension(fileName);
            if (metadata == null) {
                return new ImageInfo(fileName, type, width, height, size, dpiX, dpiY);
            }

            String formatName = metadata.getNativeMetadataFormatName();
            IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(formatName);
            IIOMetadataNode dimension = (IIOMetadataNode) root.getElementsByTagName("Dimension").item(0);
            dpiX = getDpi(dimension, "HorizontalPixelSize");
            dpiY = getDpi(dimension, "VerticalPixelSize");
            iis.close();
            return new ImageInfo(fileName, type, width, height, size, dpiX, dpiY);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Deprecated
    private static float getDpi(final IIOMetadataNode dimension, final String elementName) {
        // NOTE: The standard metadata format has defined dimension to pixels per millimeters, not DPI...
        NodeList pixelSizes = dimension.getElementsByTagName(elementName);
        IIOMetadataNode pixelSize = pixelSizes.getLength() > 0 ? (IIOMetadataNode) pixelSizes.item(0) : null;
        return pixelSize != null ? Float.parseFloat(pixelSize.getAttribute("value")) : -1;
    }
}
